#pragma once
#include "logtxt.hpp"
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// 封装网络接口
Log lg;
enum
{
    SOCKET_ERR = 1,
    BIND_ERR,
    LISTEN_ERR
};
class Sock
{
private:
    /* data */
    int listensockfd_;

public:
    Sock()
    {
    }
    void Socket()
    {
        listensockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (listensockfd_ < 0)
        {
            lg(fatal, "socket fail,errno:%d,streeor:%s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        lg(Info, "socket success,errno:%d,streeor:%s", errno, strerror(errno));
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = INADDR_ANY;

        int n = bind(listensockfd_, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            lg(fatal, "bind fail,errno:%d,streeor:%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success,errno:%d,streeor:%s", errno, strerror(errno));
    }

    void Listen()
    {
        int backlog = 10;
        if (listen(listensockfd_, backlog) < 0) // 将主动文件描述符转化为被动描述符，监听连接请求
        {
            lg(fatal, "listen error, errno: %d, errstring: %s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
        lg(Info, "listen success,errno:%d,streeor:%s", errno, strerror(errno));
    }

    int Accept(string &clientip, uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        socklen_t len = sizeof(peer);
        int sockfd_ = accept(listensockfd_, (struct sockaddr *)&peer, &len);
        if (sockfd_ < 0)
        {
            lg(Warning, "accept error, errno: %d, errstring: %s", errno, strerror(errno));
            return -1;
        }

        char buffer[32];
        inet_ntop(AF_INET, &peer.sin_addr, buffer, sizeof(buffer));
        clientip = buffer;
        port = ntohs(peer.sin_port);
        return sockfd_;
    }

    bool Connect(const string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &peer.sin_addr);
        int n = connect(listensockfd_, (struct sockaddr *)&peer, sizeof(peer));
        if (n < 0)
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }

        return true;
    }
    int Fd()
    {
        return listensockfd_;
    }
    void Close()
    {
        close(listensockfd_);
    }

    ~Sock()
    {
    }
};
